import { defineComponent, ref, computed, nextTick, watchEffect, createVNode, createTextVNode } from 'vue';
import TagGroup from '../TagGroup/index.js';
import Input from '../FormElements/Input/index.js';
import { FeatherXCircle } from 'cui-vue-icons/feather';

const Value = /* @__PURE__ */ defineComponent({
  props: {
    prepend: {
      type: [String, Number, Object]
    },
    text: {
      type: [String, Object, Array]
    },
    clearable: {
      type: Boolean
    },
    icon: {
      type: Object
    },
    disabled: {
      type: Boolean
    },
    size: {
      type: String
    },
    multi: {
      type: Boolean
    },
    showMax: {
      type: [Number, String]
    },
    onlyInput: {
      type: Boolean
    },
    placeholder: {
      type: String
    },
    valueClosable: {
      type: Boolean
    },
    filter: {
      type: Boolean
    },
    query: {
      type: Object
    },
    showMore: {
      type: Boolean
    },
    tagRender: {
      type: Function
    }
  },
  emits: ['clear', 'input', 'close', 'deleteLastValue'],
  setup(props, {
    slots,
    emit
  }) {
    const query = props.query ?? ref('');
    const filterStr = ref('');
    const filterInput = ref();
    const selection = ref();
    const onClear = e => {
      e.stopImmediatePropagation && e.stopImmediatePropagation();
      e.preventDefault && e.preventDefault();
      e.stopPropagation && e.stopPropagation();
      emit('clear', e);
    };
    const classList = () => ({
      'cm-field-value': true,
      'cm-field-clearable': props.clearable && !!props.text && !!props.text?.length,
      'cm-field-disabled': props.disabled,
      [`cm-field-value-${props.size}`]: !!props.size
    });
    const multiText = computed(() => {
      nextTick(() => {
        if (props.filter && filterInput.value) {
          const input = filterInput.value.getInput();
          input.focus();
        }
      });
      if (props.multi && props.text && props.text instanceof Array) {
        return props.text.map((item, index) => {
          return {
            id: item.id,
            title: props.tagRender?.(item) || item.title
          };
        });
      }
      return [];
    });
    const inputStyle = () => {
      // 查询内容变化时，更新输入框的宽度
      return {
        width: '10px'
        // width: str !== undefined ? str.length * 12 + 20 + 'px' : '100%',
      };
    };
    const updateFilterStyle = () => {
      if (!filterInput.value) {
        return;
      }
      const inputEl = filterInput.value.getInput();
      inputEl.style.width = '10px';
      inputEl.style.width = inputEl.scrollWidth + 'px';
      Promise.resolve().then(() => {
        inputEl.style.width = '10px';
        const maxWidth = Math.floor(selection.value?.getBoundingClientRect().width || 10);
        inputEl.style.width = inputEl.scrollWidth + 'px';
        inputEl.parentElement.style.width = Math.min(maxWidth - 20, inputEl.scrollWidth) + 'px';
      });
    };
    watchEffect(() => {
      query.value;
      filterStr.value = query.value;
      updateFilterStyle();
    });

    // 因为Input输入中文时不会触发change事件，所以需要监听input事件进行更新
    const onFilterChange = (v, e) => {
      updateFilterStyle();
      filterStr.value = v;
    };
    const onValueClick = () => {
      if (props.filter && filterInput.value) {
        const input = filterInput.value.getInput();
        input.focus();
      }
    };
    const onFilterKeyDown = e => {
      const queryStr = query.value;
      if (e.key === 'Backspace' || e.code === 'Backspace' || e.key === 'Delete' || e.code === 'Delete') {
        if (queryStr.length === 0) {
          emit('deleteLastValue');
        }
      }
    };
    const onFilterBlur = () => {
      if (props.onlyInput) {
        return;
      }
      if (props.filter) {
        filterStr.value = '';
        // setTimeout(() => {
        //     query.value = '';
        // }, 100);
      }
    };
    const onQueryChange = v => {
      query.value = v;
    };
    return () => createVNode("div", {
      "class": classList(),
      "tab-index": "1",
      "onClick": onValueClick
    }, [createVNode("input", {
      "type": "hidden"
    }, null), createVNode("span", {
      "style": {
        width: '0px',
        "font-size": '12px',
        visibility: 'hidden',
        'line-height': 'initial'
      }
    }, [createTextVNode("A")]), props.prepend ? createVNode("div", {
      "class": "cm-field-prepend"
    }, [props.prepend]) : null, props.multi ? createVNode("div", {
      "class": "cm-field-selection",
      "ref": selection
    }, [createVNode(TagGroup, {
      "data": multiText.value,
      "closable": props.valueClosable,
      "max": props.showMax,
      "showMore": props.showMore,
      "onClose": (...args) => emit('close', ...args),
      "size": props.size === 'small' ? 'small' : 'large',
      "extra": props.filter ? createVNode(Input, {
        "ref": filterInput,
        "style": inputStyle(),
        "class": "cm-select-filter",
        "trigger": "input",
        "size": props.size,
        "modelValue": filterStr.value,
        "onUpdate:modelValue": $event => filterStr.value = $event,
        "onChange": onQueryChange,
        "onKeyDown": onFilterKeyDown,
        "onInput": onFilterChange,
        "onBlur": onFilterBlur
      }, null) : null
    }, null)]) : createVNode("div", {
      "class": "cm-field-text",
      "ref": selection
    }, [!props.onlyInput ? props.text ? createVNode("span", {
      "style": {
        display: filterStr.value ? 'none' : 'inline-block'
      }
    }, [props.text]) : createVNode("span", {
      "class": "cm-field-placeholder",
      "style": {
        display: filterStr.value ? 'none' : 'inline-block'
      }
    }, [props.placeholder ?? '']) : null, props.filter ? createVNode(Input, {
      "ref": filterInput,
      "style": inputStyle(),
      "class": "cm-select-filter",
      "trigger": "input",
      "size": props.size,
      "modelValue": filterStr.value,
      "onUpdate:modelValue": $event => filterStr.value = $event,
      "onChange": onQueryChange,
      "onInput": onFilterChange,
      "onBlur": onFilterBlur
    }, null) : null]), createVNode("span", {
      "class": "cm-field-cert"
    }, [props.icon]), props.clearable && props.text && props.text !== '' ? createVNode(FeatherXCircle, {
      "class": "cm-field-clear",
      "onClick": onClear
    }, null) : null]);
  }
});

export { Value };
